﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFInvest.Security.Contracts;
using System.Security.Principal;
using System.ServiceModel;
using System.Security.Permissions;
using System.ServiceModel.Activation;

namespace WCFInvest.Security.ServicesImpl
{ 
    public class SampleService:ISample
    { 
        [PrincipalPermission(SecurityAction.Demand,Name=@"ctxus\dingyuliang")]
        public string GetSecretCode()
        {
            Console.WriteLine("GetSecretCode Required");
            DisplaySecurityDetails();
            return "The Secret Code";
        }

        [PrincipalPermission(SecurityAction.Demand, Name = @"ctxus\dingyuliang")]
        public string GetMemberCode()
        {
            Console.WriteLine("GetMemberCode Required");
            DisplaySecurityDetails();
            return "The Member Code";
        }

        [PrincipalPermission(SecurityAction.Demand, Name = @"ctxus\dingyuliang")]
        [PrincipalPermission(SecurityAction.Demand, Name = @"ctxus\ctxtester")]
        public string GetPublicCode()
        {
            Console.WriteLine("GetPublicCode Required");
            DisplaySecurityDetails();
            return "The Public Code";
        }

        private static void DisplaySecurityDetails()
        {

            Console.WriteLine("at: {0}:",DateTime.Now);

            WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
            Console.WriteLine("Windows Identity = " + windowsIdentity.Name);
            
            IPrincipal threadPrincipal = System.Threading.Thread.CurrentPrincipal;
            Console.WriteLine("Thread CurrentPrincipal Identity = " + threadPrincipal.Identity.Name);

            IIdentity primaryIdentity = ServiceSecurityContext.Current.PrimaryIdentity;
            Console.WriteLine("ServiceSecurityContext Primary Identity = " + primaryIdentity.Name);

            IIdentity serviceWindowsIdentity = ServiceSecurityContext.Current.WindowsIdentity;
            Console.WriteLine("ServiceSecurityContext Windows Identity = " + serviceWindowsIdentity.Name);

            Console.WriteLine();
        }
    }
}
